package com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.adapter.SubjectChooseItemAdapter;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.adapter.SubjectImgAdapter;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type.utils.AnswerCallback;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type.utils.ScoreUtil;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type.utils.SubjectTypeUtil;
import com.dayaokeji.rhythmschoolstudent.utils.AndroidUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ObjectUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.wiget.WrapLinearLayoutManager;
import com.dayaokeji.server_api.domain.ExamQuestion;
import com.dayaokeji.server_api.domain.SubjectAnswer;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;

/**
 * 选择题
 */
public class ChooseSubjectFragment extends BaseSubjectFragment {

    @BindView(R.id.rv_subject_choose_items)
    RecyclerView rvSubjectChooseItems;
    @BindView(R.id.tv_subject_type)
    TextView tvSubjectType;
    @BindView(R.id.tv_subject_score)
    TextView tvSubjectScore;
    @BindView(R.id.iv_subject_state)
    ImageView ivSubjectState;

    private ExamQuestion examQuestion;
    private SubjectAnswer subjectAnswer = new SubjectAnswer();
    private SubjectChooseItemAdapter subjectChooseItemAdapter;
    private final SubjectImgAdapter subjectImgAdapter = new SubjectImgAdapter();
    private TextView tvSubjectContent;
    private RecyclerView rvSubjectImages;
    private String answer;


    public static ChooseSubjectFragment newInstance(ExamQuestion examQuestion) {
        Bundle args = new Bundle();
        args.putSerializable(EXTRA_EXAM_ENTITY,examQuestion);
        ChooseSubjectFragment fragment = new ChooseSubjectFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    protected View onCreate(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_choose_subject, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
    }

    private void init() {
        examQuestion = (ExamQuestion) getArguments().getSerializable(EXTRA_EXAM_ENTITY);
        if (examQuestion == null) {
            ToastUtils.warning(R.string.data_incorrect);
            return;
        }
        subjectChooseItemAdapter = new SubjectChooseItemAdapter(subjectAnswer,examQuestion.getType(),isExamResult(),isShowResult());
        subjectChooseItemAdapter.addHeaderView(createHeaderPaddingView());
        subjectChooseItemAdapter.setHeaderView(createHeaderView());
        setupView();
        setupViewData();
        if (!isExamResult()) {
            setOnListener();
        }
    }

    private void setupView() {
        final WrapLinearLayoutManager wrapLinearLayoutManager = new WrapLinearLayoutManager(getActivity());
        rvSubjectChooseItems.setLayoutManager(wrapLinearLayoutManager);
        rvSubjectChooseItems.setAdapter(subjectChooseItemAdapter);
        rvSubjectImages.setLayoutManager(new GridLayoutManager(getActivity(),4));
        rvSubjectImages.setAdapter(subjectImgAdapter);
        setNavigationShowImage(subjectImgAdapter);
    }

    private void setupViewData() {
        tvSubjectType.setText(getSubjectTypeStr(examQuestion.getType()));
        tvSubjectScore.setText(String.format("分值：%s 分", ScoreUtil.doubleTrans(examQuestion.getScore())));
        tvSubjectContent.setText(examQuestion.getContent());
        subjectImgAdapter.setNewData(examQuestion.getResourceList());
        subjectChooseItemAdapter.setNewData(examQuestion.getChoiceInfoList());
        subjectAnswer.setExamQuestionId(examQuestion.getId());

        if (isExamResult()) {
            if (examQuestion.getGetScore() > 0){
                ivSubjectState.setImageResource(R.mipmap.ic_subject_success);
            }else{
                ivSubjectState.setImageResource(R.mipmap.ic_subject_error);
            }
        }
        if (examQuestion.getSubjectAnswer() != null) {
            examQuestion.setStudentAnswer(examQuestion.getSubjectAnswer().getAnswer());
        }

        if (isShowResult()) {
            answer = examQuestion.getCorrectAnswer();
            ivSubjectState.setVisibility(View.GONE);
        }else{
            if (isExamResult()) {
                ivSubjectState.setVisibility(View.VISIBLE);
            }
            answer = examQuestion.getStudentAnswer();
        }
        if (examQuestion.getType() == SubjectTypeUtil.SINGLE_CHOOSE) {
            subjectAnswer.setAnswer(answer);
        }else{
            if (!TextUtils.isEmpty(answer)) {
                subjectAnswer.setAnswer(answer);
                if (answer.contains(",")) {
                    final String[] strings = answer.split(",");
                    final List<String> answers = new ArrayList<>();
                    for (String string : strings) {
                        answers.add(string);
                    }
                    subjectAnswer.setChooseIndex(answers);
                }else{
                    subjectAnswer.setChooseIndex(new ArrayList<String>(Arrays.asList(answer)));
                }
            }
        }
        callbackResult(subjectAnswer);
    }

    private void setOnListener() {
        subjectChooseItemAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                final ExamQuestion.ChoiceInfo choiceInfo = (ExamQuestion.ChoiceInfo) adapter.getData().get(position);
                final String index = choiceInfo.getIndex();
                if (examQuestion.getType() == SubjectTypeUtil.SINGLE_CHOOSE) {
                    subjectAnswer.setAnswer(index);
                }else{
                    as(index);
                }
                if (getActivity() != null) {
                    if (getActivity() instanceof AnswerCallback) {
                        ((AnswerCallback) getActivity()).callback(subjectAnswer);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
        subjectChooseItemAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                final ExamQuestion.ChoiceInfo choiceInfo = (ExamQuestion.ChoiceInfo) adapter.getData().get(position);
                final String index = choiceInfo.getIndex();
                if (examQuestion.getType() == SubjectTypeUtil.SINGLE_CHOOSE) {
                    subjectAnswer.setAnswer(index);
                }else{
                    as(index);
                }
                if (getActivity() != null) {
                    if (getActivity() instanceof AnswerCallback) {
                        ((AnswerCallback) getActivity()).callback(subjectAnswer);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 多选
     * @param index
     */
    private void as(String index) {
        final List<String> chooseIndex = subjectAnswer.getChooseIndex();
        if (chooseIndex.contains(index)) {
            chooseIndex.remove(index);
        }else{
            chooseIndex.add(index);
        }
        StringBuilder builder = new StringBuilder();
        for (String s : chooseIndex) {
            builder.append(s);
            builder.append(",");
        }
        final String s = builder.toString();
        if (TextUtils.isEmpty(s)) {
            subjectAnswer.setAnswer("");
        }else{
            final int i = s.lastIndexOf(",");
            final CharSequence charSequence;
            if (i > 0) {
                charSequence = s.subSequence(0, i);
            }else{
                charSequence = s;
            }
            subjectAnswer.setAnswer(charSequence.toString());
        }

    }


    /***********************************************************************************************
     *  recycler view header
     *  ********************************************************************************************
     */

    private View createHeaderView() {
        View headerViewRoot = getLayoutInflater().inflate(R.layout.exam_choose_header_layout, null, false);
        tvSubjectContent = headerViewRoot.findViewById(R.id.tv_subject_content);
        rvSubjectImages = headerViewRoot.findViewById(R.id.rv_subject_imgs);
        return headerViewRoot;
    }

    private  View createHeaderPaddingView() {
        View view = new View(getContext());
        view.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, AndroidUtils.dp2px(10)));
        return view;
    }

}
